<template>
  <el-form ref="myform" :model="formItem" :rules="rules" label-width="auto" size="mini" class="model-edit-form">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="模具名" prop="modelName" required>
          <el-input v-model="formItem.modelName" placeholder="请输入模具名" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="模具编码" prop="modelCode" required>
          <el-input v-model="formItem.modelCode" placeholder="请输入模具编码" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="模具类别" prop="typeId" required>
          <el-select v-model="formItem.typeId" placeholder="请选择模具类别">
            <el-option
              v-for="item in availableModelTypes"
              :key="item.code"
              :label="item.text"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="长度" prop="length" required>
          <el-input v-model="formItem.length" placeholder="请输入长度" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="宽度" prop="width" required>
          <el-input v-model="formItem.width" placeholder="请输入宽度" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="高度" prop="height" required>
          <el-input v-model="formItem.height" placeholder="请输入高度" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="预览图" prop="imgUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <el-image v-if="formItem.imgUrl" :src="fileUrl(formItem.imgUrl)" fit="cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="小地图" prop="mapUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleMapSuccess"
          >
            <el-image v-if="formItem.mapUrl" :src="fileUrl(formItem.mapUrl)" fit="cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="3D模型文件">
          <el-table :data="formItem.versionList" style="width: 100%" :show-header="false">
            <el-table-column
              prop="versionCode"
              label="版本类型"
            >
              <template slot-scope="{row}">
                <el-select v-model="row.versionCode" size="mini" placeholder="请选择">
                  <el-option
                    v-for="item in availableVersionTypes"
                    :key="item.code"
                    :label="item.text"
                    :value="item.code"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="fileName"
              label="文件名"
            >
              <template slot-scope="{row}">
                <a :href="fileUrl(row.fileUrl)" download>{{ row.fileName }}</a>
              </template>
            </el-table-column>
            <el-table-column label="" align="center" class-name="small-padding fixed-width">
              <template slot-scope="{row}">
                <el-button title="删除" type="text" size="mini" icon="el-icon-delete" @click="remove3dFile(row)" />
              </template>
            </el-table-column>
            <div slot="empty">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handle3DSuccess"
              >
                <i class="el-icon-plus" />上传3D文件
              </el-upload>
            </div>
          </el-table>
          <el-upload
            v-if="formItem.versionList.length > 0 && formItem.versionList.length < availableVersionTypes.length"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handle3DSuccess"
          >
            <i class="el-icon-plus" />上传3D文件
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import { getToken } from '@neu/biz-core/utils/auth'
import { create, update, detail } from '@neu/dcvm-ui/api/model'
import { uploadUrl, downloadFileUrl } from '@neu/dcvm-ui/api/file'
import { listOfType } from '@neu/dcvm-ui/api/dictionary'

// 定义一个表单原始项
const formItem = {
  modelName: '',
  modelCode: '',
  typeId: '1',
  length: 0,
  width: 0,
  height: 0,
  imgUrl: '',
  mapUrl: '',
  versionList: []
}

const rules = {
  modelName: [
    { required: true, message: '模具名不能为空', trigger: 'blur' }
  ],
  modelCode: [
    { required: true, message: '模具编码不能为空', trigger: 'blur' }
  ],
  typeId: [
    { required: true, message: '模具类别不能为空', trigger: 'blur' }
  ]
}

export default {
  name: 'ModelsEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        ...rules
      },
      availableModelTypes: [],
      availableVersionTypes: [],
      uploadUrl: uploadUrl
    }
  },
  computed: {
    edited() {
      return this.id !== -1
    },
    uploadHeaders: function() {
      return {
        'Authentication': getToken()
      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function(newVal, oldVal) {
      if (newVal > -1) {
        this.fetch()
      }
    }
  },
  created() {
    listOfType('modelType').then(response => {
      this.availableModelTypes = response.data
    })
    listOfType('versionType').then(response => {
      this.availableVersionTypes = response.data
    })
    if (this.id > -1) {
      this.fetch()
    }
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.edited
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    handleAvatarSuccess(response) {
      this.formItem.imgUrl = response.data.fsId
    },
    handleMapSuccess(response) {
      this.formItem.mapUrl = response.data.fsId
    },
    handle3DSuccess(response) {
      const { fsId, name } = response.data
      const version = {
        fileUrl: fsId,
        versionCode: '',
        fileName: name
      }
      if (this.formItem.versionList.findIndex(it => it.fileUrl === fsId) === -1) {
        this.formItem.versionList.push(version)
      }
    },
    fileUrl(fsId) {
      return downloadFileUrl(fsId)
    },
    remove3dFile(row) {
      this.formItem.versionList = this.formItem.versionList.filter(it => it.fileUrl !== row.fileUrl)
    }
  }
}
</script>

<style lang="scss">
  .model-edit-form {
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 128px;
      height: 128px;
      line-height: 128px;
      text-align: center;
    }
    .avatar {
      width: 128px;
      height: 128px;
      display: block;
    }
  }

</style>
